package com.fxwater.websocket.job;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.fxwater.websocket.util.SpringBeanFinder;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Description: 工艺图数据生成作业类
 * @Author: 王明朝
 * @Date: 2019/8/18 1:04
 */
public class ScheduledProcessFlowDiagramGenerateJob implements Job {

    private final long DELAY = 1000;

    private final String[] measureObjects = SelectRealData.selectAllItemCode();

    private static Logger logger = LoggerFactory.getLogger(ScheduledProcessFlowDiagramGenerateJob.class);

    /*private final String[] measureObjects = new String[]{
            "AN_Flow_1",
            "AN_Flow_Sum_1",
            "CL_Flow_1",
            "CL_Flow_2",
            "CL_Flow_Sum_1",
            "CL_Flow_Sum_2",
            "In_Flow",
            "In_Flow_Sum",
            "In_Pressure",
            "In_Turb",
            "In_YL",
            "Level_An_1",
            "Level_An_2",
            "Level_Cl_1",
            "Level_Cl_2",
            "Level1",
            "Level2",
            "Out_Flow",
            "Out_Flow_Sum",
            "Out_Pressure",
            "Out_Turb",
            "Out_YL"
    };*/


    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        ThreadPoolExecutor executor =new ThreadPoolExecutor(1, 1,
                0L, TimeUnit.MILLISECONDS,
                new LinkedBlockingQueue<Runnable>());
        executor.execute(new Runnable() {
            @Override
            public void run() {
                logger.info("开始执行第三场景数据缓存");
                RedisTemplate<String, Serializable> redisTemplate = SpringBeanFinder.findBean("stringRedisTemplate");
                JdbcTemplate jdbcTemplate = SpringBeanFinder.findBean(JdbcTemplate.class);
                while(redisTemplate==null|| jdbcTemplate==null){
                    try {
                        Thread.sleep(DELAY);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    redisTemplate = SpringBeanFinder.findBean(RedisTemplate.class);
                    jdbcTemplate = SpringBeanFinder.findBean(JdbcTemplate.class);
                }
                String sql = "select pump_name,pump_code from fx_pump_station";
                List<Map<String,Object>> pumpStationList = jdbcTemplate.queryForList(sql);
                logger.info("系统泵站信息：{}",pumpStationList);
                final JdbcTemplate myJdbcTemplate = jdbcTemplate;
                final RedisTemplate<String, Serializable> myRedisTemplate = redisTemplate;
                if(CollectionUtil.isNotEmpty(pumpStationList)){
                    pumpStationList.forEach(map->{
                        String pompCode = String.valueOf(map.get("pump_code"));
                        logger.info("开始缓存场景三，泵站【{}】的数据",pompCode);
                        if(StrUtil.isNotEmpty(pompCode) && !"null".equals(pompCode)){
                            for(String obj:measureObjects){
                                if(!obj.contains(pompCode)){
                                    continue;
                                }
                                logger.info("开始缓存场景三，泵站【{}】,测量量【{}】的数据",pompCode,obj);
                                DateTime dateTime =  DateUtil.beginOfDay(new Date());
                                java.sql.Date correntDate = dateTime.toSqlDate();
                                String querySql="SELECT " +
                                        "r.item_val,r.item_code,i.item_name," +
                                        "LEFT ( CONVERT ( VARCHAR ( 100 ), r.lastchange, 24 ), 5 ) lastchange," +
                                        "(" +
                                        "CASE " +
                                        "WHEN ( i.is_flag_warning= 1 AND r.item_val> 0 ) THEN" +
                                        " 1 " +
                                        " WHEN ( i.is_updown_warning= 1 AND ( r.item_val< i.fz_down OR r.item_val> i.fz_up ) ) THEN " +
                                        " 2 ELSE 0  " +
                                        " END  " +
                                        " ) is_warning ,i.unit_zh,i.unit_flag  " +
                                        " FROM " +
                                        " fx_real_data r " +
                                        " LEFT JOIN fx_item i ON r.item_code= i.item_code  " +
                                        " WHERE " +
                                        " i.pump_code=? " +
                                        " AND r.item_code = ?  " +
                                        " AND r.lastchange>=?";
                                logger.info("第三场景开始查询数据库，查询语句<{}>,查询参数[{}|{}|{}]",querySql,pompCode,obj,correntDate);
                                List<Map<String,Object>> list = myJdbcTemplate.queryForList(querySql,pompCode,obj,correntDate);
                                obj=obj.split("\\.")[1];
                                if(CollectionUtil.isNotEmpty(list)) {
                                    logger.info("第三场景查询数据库结果数量："+list.size());
                                    Map<String, Object> data = list.get(0);
                                    String date = dateTime.toString("yyyyMMdd");
                                    String prefix = "THIRD_" + pompCode + "_" + date;
                                    String redisFlag = prefix + "_" + obj + "_LAST_UPDATE";
                                    String currenTime = String.valueOf(data.get("lastchange"));
                                    if (myRedisTemplate.hasKey(redisFlag)) {
                                        String lastTime = (String) myRedisTemplate.opsForValue().get(redisFlag);
                                        if (lastTime.equals(currenTime)) {
                                            continue;
                                        }
                                    }
                                    myRedisTemplate.opsForValue().set(redisFlag, currenTime);
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);
                                    redisFlag = prefix + "_" + obj+"_VAL";
                                    String itemVal =  String.valueOf(data.get("item_val"));
                                    itemVal = NumberUtils.formatNumber(itemVal);
                                    myRedisTemplate.opsForValue().set(redisFlag,itemVal);
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);

                                    redisFlag = prefix + "_" + obj+"_item_name";
                                    myRedisTemplate.opsForValue().set(redisFlag, String.valueOf(data.get("item_name")));
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);

                                    redisFlag = prefix + "_" + obj+"_unit_zn";
                                    String unitZn =data.get("unit_zh")!=null? String.valueOf(data.get("unit_zh")):"";
                                    myRedisTemplate.opsForValue().set(redisFlag, unitZn);
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);


                                    redisFlag = prefix + "_" + obj+"_unit_flag";
                                    String unitFlag = data.get("unit_flag")!=null?String.valueOf(data.get("unit_flag")):"";
                                    myRedisTemplate.opsForValue().set(redisFlag, unitFlag);
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);

                                    String val_ = itemVal;
                                    if(StrUtil.isNotEmpty(unitZn)){
                                        val_+=unitZn;
                                    }else if(StrUtil.isNotEmpty(unitFlag)){
                                        val_+=unitFlag;
                                    }


                                    redisFlag = prefix + "_" + obj+"_VAL_";
                                    myRedisTemplate.opsForValue().set(redisFlag, val_);
                                    myRedisTemplate.expire(redisFlag, 1, TimeUnit.DAYS);
                                }else {
                                    logger.error("第三场景未查询数据库结果！");
                                }
                            }
                        }
                    });
                    logger.info("结束执行第三场景数据缓存！");
                }
            }
        });
    }
}
